package com.etooling.framework.controller;

import com.etooling.framework.entity.*;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.*;
import com.etooling.framework.service.FileUploadSaveService;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.PasswordRuleMgr;
import com.etooling.framework.utils.VerifyCodeUtils;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/admin/userMgr")
/**
 * @title: EmployeeController
 * @description: 用户管理
 * @author 周志荣
 * @date 2020/12/18 17:56
 */
public class EmployeeController {
    @Autowired
    EmployeeRepository employeeRepository;


    @RequestMapping("pageQuery")
    @ResponseBody
    /**
     　　 @description:
    　　 @param [request, FileResource, pageSize, page, isUnion, searchName]
    　　 @return com.irobot.framework.svo.ReplyObj
    　　 @throws
    　　 @author 周志荣
    　　 @date 2020/12/20 18:25
    　　*/
    ReplyObj pageQuery(HttpServletRequest request,
                       @RequestParam(defaultValue = "", required = false, value = "orgId") String orgId,
                       @RequestParam(defaultValue = "30", required = false, value = "pageSize") int pageSize,
                       @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                       @RequestParam(defaultValue = "", required = false, value = "searchValue") String searchValue,
                       @RequestParam(defaultValue = "", required = false, value = "searchAll") String searchAll,
                       @RequestParam(required = false, value = "craftIds") String[] craftIds
    ) {
        String companyId = (String) WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");//使用一个序
        //分页
        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);
        JpaQueryBuilder pb = Specifications.<LoginLog>and();
        pb.eq("companyId", companyId);
        pb.eq("status", "启用");
        if (WebUtils.checkStr(orgId)) {
            List sonOrgList = orgRepository.getOrgChildrenIdByParentId(orgId, companyId);
            pb.in("org.id", sonOrgList);
        }
        if (WebUtils.checkStr(searchValue)) {
            pb.predicate(Specifications.or()
                    .like("name", "%" + searchValue + "%")
                    .like("mobile", "%" + searchValue + "%")
                    .like("loginId", "%" + searchValue + "%")
                    .build());
        }
        Page<Employee> pageList = employeeRepository.findAll(pb.build(), pageable);
        return WebUtils.flushSuccess(pageList);
    }

    @Autowired
    FileResourceRepository fileResourceRepository;
    @Autowired
    AttachFileRepository attachFileRepository;

    @RequestMapping("uploadAvatar")
    @ResponseBody
    ReplyObj uploadAvatar(HttpServletRequest request
    ) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("avatarFile");
        if (uploadFile.isEmpty() == false) {
            String originalFilename = uploadFile.getOriginalFilename();
            String compCode = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }
                if (!uploadFile.isEmpty()) {
                    //拿出现在应用的文件存储方式
                    FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                    String uploadImplClass = fileResource.getImplClassName();
                    FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(uploadImplClass).getDeclaredConstructor().newInstance();
                    AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);
                    return WebUtils.flushObjSuccess(attachFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure();
            }
        }

        return WebUtils.flushFailure();
    }

    @RequestMapping("resetPwd")
    @ResponseBody
    ReplyObj resetPwd(HttpServletRequest request,
                      @RequestParam(defaultValue = "", required = false, value = "initPwd") String initPwd,
                      @RequestParam(defaultValue = "", required = false, value = "newPwd") String newPwd
    ) {
        Employee loginUser = employeeRepository.getOne(WebUtils.getSessionValue(request, WebUtils.LOGIN_USER_KEY));
        Employee po = employeeRepository.getOneByLoginId(loginUser.getLoginId());
        String randomCode = po.getRandCode();
        String tmpPwd = initPwd + randomCode;
        String password = PasswordRuleMgr.getCryptoPassword(tmpPwd);
        System.out.println(password);
        if (password.equals(po.getPwd()) || initPwd.equals(po.getPwd())) {
            randomCode = VerifyCodeUtils.generateVerifyCode(4);
            System.out.println(randomCode);
            po.setRandCode(randomCode);
            tmpPwd = newPwd + randomCode;
            System.out.println(tmpPwd);
            password = PasswordRuleMgr.getCryptoPassword(tmpPwd);
            System.out.println(password);
            po.setPwd(password);
            employeeRepository.save(po);
            return WebUtils.flushSuccess();
        } else {
            return WebUtils.flushFailure("原密码错误!");
        }
    }

    @Autowired
    OrgRepository orgRepository;

    @RequestMapping("add")
    @ResponseBody
    ReplyObj add(HttpServletRequest request, Employee vo,
                 @RequestParam(defaultValue = "", required = false, value = "newPassWord") String newPassWord,
                 @RequestParam(defaultValue = "", required = false, value = "imgFileId") String imgFileId,
                 @RequestParam(defaultValue = "", required = false, value = "orgId") String orgId) {
        Employee haveLoginIdUser = employeeRepository.getOneByLoginId(vo.getLoginId(), orgId);


        if (haveLoginIdUser != null) {
            return WebUtils.flushFailure(vo.getLoginId() + "帐号已经存在");
        } else {
            if (WebUtils.checkStr(imgFileId)) {
                vo.setAvatar(attachFileRepository.getOne(imgFileId));
            }
            String pwd = "88888888";
            if (WebUtils.checkStr(newPassWord)) {
                pwd = newPassWord;

            }
            Org org = orgRepository.getOne(orgId);
            vo.setPwd(pwd);
            vo.setOrg(org);
            vo.setCompanyId(org.getCompanyId());
            vo.setCreateTime(new Date());
            employeeRepository.saveAndFlush(vo);
            return WebUtils.flushSuccess();
        }

    }


    @RequestMapping("update")
    @ResponseBody
        /*
         * @description: 修改机构
         * @param [request, org, newOrgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 18:13
         */
    ReplyObj update(HttpServletRequest request, Employee vo,
                    @RequestParam(defaultValue = "", required = false, value = "imgFileId") String imgFileId,
                    @RequestParam(defaultValue = "", required = false, value = "newPassWord") String newPassWord) {
        try {
            Employee po = employeeRepository.findById(vo.getId()).get();
            po = (Employee) VoToPoUtil.copyProperties(po, vo, new String[]{"companyId","org", "roles", "randCode", "pwd", "haveCraft", "createTime"});

            if (WebUtils.checkStr(newPassWord)) {
//                String randomCode = VerifyCodeUtils.generateVerifyCode(4);
//                System.out.println(randomCode);
//                po.setRandCode(randomCode);
//                String tmpPwd = newPassWord + randomCode;
//                System.out.println(tmpPwd);
//                String password = PasswordRuleMgr.getCryptoPassword(tmpPwd);
//                System.out.println(password);
//                po.setPwd(password);
                po.setPwd(newPassWord);
            }
            if (WebUtils.checkStr(imgFileId)) {
                po.setAvatar(attachFileRepository.getOne(imgFileId));
            }
            System.out.println(newPassWord);
            employeeRepository.saveAndFlush(po);
            return WebUtils.flushObjSuccess(po);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure("数据错误，请联系统管理员");
        }
    }

    @RequestMapping("del")
    @ResponseBody
    ReplyObj del(HttpServletRequest
                         request, @RequestParam(defaultValue = "", required = false, value = "id") String id) {
        try {
            employeeRepository.deleteById(id);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            Employee po = employeeRepository.findById(id).get();
            po.setStatus("禁用");
            employeeRepository.save(po);
            return WebUtils.flushSuccess();
        }

    }

    @Autowired
    RoleRepository roleRepository;

    @RequestMapping("/saveRoles")
    @ResponseBody
    ReplyObj saveRoles(HttpServletRequest
                               request,
                       @RequestParam(defaultValue = "", required = false, value = "userId") String userId,
                       @RequestParam(defaultValue = "", required = false, value = "roleIds") String roleIds) {
        try {
            List resultList = new ArrayList<>(Arrays.asList(roleIds.split(",")));
            List<Role> roleList = roleRepository.getByIds(resultList);
            Employee employee = employeeRepository.getOne(userId);
            employee.setRoles(roleList);
            employeeRepository.save(employee);
            return WebUtils.flushObjSuccess(roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }


    public static void main(String[] args) {
        String randomCode = "DFKS";
        System.out.println(randomCode);

        String tmpPwd = "qwer1234" + randomCode;
        System.out.println(tmpPwd);
        String password = PasswordRuleMgr.getCryptoPassword(tmpPwd);
        System.out.println(password);
    }



}
